# 登录注册service层
from flask import jsonify
from flask_mail import Message, Mail
import random
import re
import dao.LoginDao as LoginDao
import vo.LoginVo as LoginVo


# 判断邮箱是否合法
def service_login_check_email(email):
    regex = r'\b[A-Za-z0-9._%+一]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,} \b'
    if re.fullmatch(regex, email):
        return True
    else:
        return False


# 判断密码是否合法
def service_login_check_password(password):
    # 检查长度是否为8位
    if not len(password) == 8:
        return False
    # 检查是否包含小写字母
    if not re.search(r'[a-z]',password):
        return False
    # 检查是否包含大写字母
    if not re.search(r'[A-Z]',password):
        return False
    # 检查是否包含数字
    if not re.search(r'[0-9]',password):
        return False
    # 检查是否包含特殊字符
    if re.search(r'[!@#$%^&*()_+-=,.<>?]',password):
        return False
    return True


# 数据库查验用户名和密码后，返回结果
def service_login_default(userName, passWord):
    result_dao = LoginDao.dao_login_default(userName, passWord)
    result = LoginVo.vo_login_default(result_dao)
    return result


# 数据库查验邮箱和密码后，返回结果
def service_login_email(email, passWord):
    result_dao = LoginDao.dao_login_email(email, passWord)
    result = LoginVo.vo_login_email(result_dao)
    return result


# 存入数据库，新增用户，对验证码进行检验后，返回结果
def service_login_register(email, userName, passWord, captcha):
    # 判断邮箱是否合法
    if not service_login_check_email(email):
        result = LoginVo.vo_login_default_fail()
        return jsonify(result)

    # 判断密码是否合法
    if not service_login_check_password(passWord):
        result = LoginVo.vo_login_default_fail()
        return jsonify(result)

    # 判断验证码是否正确
    if LoginDao.dao_login_verificationCode(email, captcha) is False:
        result = LoginVo.vo_login_default_fail()
        return jsonify(result)

    result_dao = LoginDao.dao_login_register(email, userName, passWord)
    result = LoginVo.vo_login_register(result_dao)
    return jsonify(result)


# 找回密码，更新密码后，返回结果
def service_login_forgotPassword(email, captcha, newPassword):
    # 判断验证码是否正确
    if LoginDao.dao_login_verificationCode(email, captcha) is False:
        result = LoginVo.vo_login_default_fail()
        return jsonify(result)

    result_dao = LoginDao.dao_login_forgotPassword(email, newPassword)
    result = LoginVo.vo_login_forgotPassword(result_dao)
    return jsonify(result)


# 验证码发送功能
def service_login_sendCaptcha(email):
    # 判断验证码是否已经被发送
    if LoginDao.dao_login_captcha(email):
        result = LoginVo.vo_login_default_fail()
        return jsonify(result)

    mail = Mail()
    captcha = str(random.randint(100000, 999999))
    msg = Message("验证码",
                  sender="jz147896325@qq.com",
                  recipients=[email],
                  body='您的验证码为：%s ，请在10分钟内使用。' % captcha)
    mail.send(msg)
    result_dao = LoginDao.dao_login_sendCaptcha(email, captcha)

    result = LoginVo.vo_login_sendCaptcha(result_dao)
    return jsonify(result)
